package com.xsdl.chain;

import com.xsdl.chain.verifier.Validator;
import com.xsdl.chain.verifier.ValidatorContext;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

public class Checker {

    private List<Validator> validatorList = new ArrayList<>();


    public void addValidator(Validator validator) {
        validatorList.add(validator);
    }

    public void validate(Object bean) throws IllegalAccessException {
        ValidatorContext context = new ValidatorContext(bean);
        Field[] fields = bean.getClass().getDeclaredFields();
        for (Field field : fields) {
            if (field.getAnnotations().length == 0) {
                continue;
            }
            field.setAccessible(true);
            for (Validator validator : validatorList) {
                if (context.getStop()) {
                    break;
                }
                validator.validate(field, field.get(bean), context);
            }
        }
        context.throwErrMsgIfNecessary();
    }

}
